package cloud.maque.admin.impl;

import cloud.maque.admin.domain.consts.ConstVar;
import cloud.maque.admin.domain.entity.MqRole;
import cloud.maque.admin.domain.request.RoleMenuRequest;
import cloud.maque.admin.domain.vo.RoleVo;
import cloud.maque.admin.mapper.MqRoleMapper;
import cloud.maque.admin.service.MqRolePrivilegeService;
import cloud.maque.admin.service.MqRoleService;
import cloud.maque.admin.service.MqUserRoleService;
import cloud.maque.framework.common.exception.BusinessException;
import cloud.maque.framework.common.request.PaginateDataResquest;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author 4color
 * @description 角色表
 * @date 2023-03-17
 */
@Service
public class MqRoleServiceImpl extends ServiceImpl<MqRoleMapper, MqRole> implements MqRoleService {


    @Autowired
    MqRolePrivilegeService rolePrivilegeService;

    @Autowired
    MqUserRoleService userRoleService;

    /**
     * @param mqRole 记录对象
     * @return
     */
    @Override
    @Transactional
    public RoleVo saveRole(RoleVo mqRole) {

        Assert.hasText(mqRole.getRoleName(), "角色名称不能为空");
        Assert.hasText(mqRole.getRoleGroupId(), "所在分组不能为空");

        //判断角色是否重复
        if (!StrUtil.isEmptyIfStr(mqRole.getRoleCode()) && !StrUtil.isEmptyIfStr(mqRole.getRoleId())) {
            MqRole oldRole = getDetailByTenandIdAndCode(mqRole.getTenantId(), mqRole.getRoleCode());
            if (oldRole != null && !oldRole.getRoleId().equals(mqRole.getRoleId())) {
                throw new BusinessException("角色代码已存在");
            }
        }

        saveOrUpdate(mqRole);

        //把权限给到菜单
        RoleMenuRequest menuRequest = new RoleMenuRequest();
        menuRequest.setRoleId(mqRole.getRoleId());
        menuRequest.setMenuIds(mqRole.getMenuIdList());
        rolePrivilegeService.addMenuForRole(menuRequest);

        return mqRole;
    }

    @Override
    @Transactional
    public Boolean delete(String roleId, String tenantId) {

        QueryWrapper<MqRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MqRole::getTenantId, tenantId);
        wrapper.lambda().eq(MqRole::getRoleId, roleId);

        if (remove(wrapper)) {
            rolePrivilegeService.deleteByRoleId(roleId);
            userRoleService.deleteByRoleId(roleId);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Integer countByGroupId(String groupId) {

        QueryWrapper<MqRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MqRole::getRoleGroupId, groupId);
        return count(queryWrapper);
    }

    @Override
    public RoleVo getDetail(String roleId) {

        RoleVo roleVo = new RoleVo();
        roleVo = roleVo.convert(this.getById(roleId));

        roleVo.setMenuIdList(rolePrivilegeService.getMenus(roleId));

        return roleVo;
    }

    @Override
    public PageInfo<MqRole> page(PaginateDataResquest<MqRole> pageReq) {

        if (pageReq != null) {
            PageHelper.startPage(pageReq.getPageIndex(), pageReq.getPageSize());
        }
        QueryWrapper<MqRole> wrapper = new QueryWrapper<>();

        if (pageReq != null && pageReq.getData() != null) {
            if (!StrUtil.isEmptyIfStr(pageReq.getData().getRoleName())) {
                wrapper.lambda().like(MqRole::getRoleName, pageReq.getData().getRoleName());
            }

            if (!StrUtil.isEmptyIfStr(pageReq.getData().getRoleCode())) {
                wrapper.lambda().like(MqRole::getRoleCode, pageReq.getData().getRoleCode());
            }

            if (!StrUtil.isEmptyIfStr(pageReq.getData().getRoleGroupId())) {
                wrapper.lambda().eq(MqRole::getRoleGroupId, pageReq.getData().getRoleGroupId());
            }

            if (!StrUtil.isEmptyIfStr(pageReq.getData().getTenantId())) {
                wrapper.lambda().eq(MqRole::getTenantId, pageReq.getData().getTenantId());
            } else {
                wrapper.lambda().eq(MqRole::getTenantId, ConstVar.NoObject);
            }
        }

        wrapper.lambda().orderByAsc(MqRole::getRoleOrder);
        wrapper.lambda().orderByAsc(MqRole::getRoleId);
        List<MqRole> lists = this.baseMapper.selectList(wrapper);
        PageInfo<MqRole> pageInfo = new PageInfo<>(lists);

        return pageInfo;
    }

    /**
     * 查询多个角色
     *
     * @param roleIds
     * @return
     */
    @Override
    public List<MqRole> getDetails(List<String> roleIds) {

        QueryWrapper<MqRole> queryWrapper = new QueryWrapper<>();

        for (String roleId : roleIds) {
            queryWrapper.lambda().or(con -> {
                con.eq(MqRole::getRoleId, roleId);
            });
        }
        return this.baseMapper.selectList(queryWrapper);
    }


    private MqRole getDetailByTenandIdAndCode(String tenantId, String roleCode) {

        QueryWrapper<MqRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MqRole::getTenantId, tenantId);
        queryWrapper.lambda().eq(MqRole::getRoleCode, roleCode);

        return this.getOne(queryWrapper, false);
    }
}
